package collection_;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

/**
 * @Author 小闽
 * @Date 2024/10/21 16:30
 * @PackageName: collection_
 * @ClassName: CollectionIterator
 * @Description:
 * @Version
 */
public class CollectionIterator_ {
    @SuppressWarnings("all")
    public static void main(String[] args) {
        Collection col = new ArrayList();
        col.add(new Book("三国演义","罗贯中",10.1));
        col.add(new Book("小李飞刀","古龙",5.1));
        col.add(new Book("红楼梦","曹雪芹",34.6));

        //System.out.println(col);
        // 现在有一个需求我想要遍历集合中的内容
        //1. 先拿到集合的迭代器，因为实现了Collection接口的实现类都必须要实现一个iterator()方法
        Iterator iterator = col.iterator();
        //2. 使用while循环遍历
        while (iterator.hasNext()) { // 使用iterator去判断集合中是否还有元素
            Object next = iterator.next(); // 如果有元素，则每次迭代取出对应的元素
            System.out.println(next);
        }
        //3. 当退出while循环后。这时iterator迭代器，指向最后的元素
        // iterator.next(); //NoSuchElementException
        //4. 如果希望再次遍历，需要重置我们的迭代器
        iterator = col.iterator();
        System.out.println("===第二次遍历===");
        while (iterator.hasNext()) {
            Object next = iterator.next();
            System.out.println(next);
        }
    }
}

class Book{
    private String name;
    private String author;
    private double price;

    public Book(String name, String author, double price) {
        this.name = name;
        this.author = author;
        this.price = price;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                '}';
    }
}
